import 'dart:io';

import 'package:get/get.dart';
import 'package:xindong/common/xindong_api_path.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/extension/extension_string.dart';
import 'package:xindong/handle/xindong_user_handle.dart';
import 'package:xindong/manager/network/xindong_networking.dart';
import 'package:xindong/manager/xindong_user_controller.dart';
import 'package:xindong/models/xindong_auth_class.dart';
import 'package:xindong/models/xindong_file_select_class.dart';
import 'package:xindong/utils/xindong_text_util.dart';

// 1实名|2学历|3车辆|4房产
class AuthType {
  static const int none = 0;
  static const int realName = 1;
  static const int education = 2;
  static const int car = 3;
  static const int house = 4;
}

class XinDongAuthCtr extends GetxController {
  static XinDongAuthCtr get to => Get.find();

  final _userHandle = XinDongUserHandle();

  List<XinDongAuthClass> dataList = [];

  // 列表
  void requestAuthList() async {
    final data = await _userHandle.userAuthList(userId: XinDongUserController.to.loginId);
    if (data.isNotEmpty) {
      dataList = data;
      update();
    }
  }

  /// 活体检测后人脸比对
  ///
  /// token 网易校验token（必传）
  /// imageUrl 认证图片地址（传：代表用于对比认证；不传：代表登录检测是不是本人操作登录）
  ///
  /// return null：为报错；isSelf=1 ：是本人，认证通过；isSelf=0：不是本人，认证不通过；isSelf=2：重复认证
  Future<void> requestAuthFace({required String token, required String imageUrl}) async {
    final object = await XinDongNetworking.instance.request(
      XinDongApi.userAuthFace,
      method: XinDongHttpMethod.post,
      parameters: {"token": token, "image": imageUrl},
    );

    if (object.code == XinDongServerStatus.success) {
      // if (object.data["isSelf"] == 1) {
      //   /// 更新数据存储
      //   QHYYAccountUser accountUser = QHYYAccountUser.current();
      //   accountUser.user.isAuth = 1;
      //
      //   /// 存储用户数据
      //   QHYYDataStorage.saveAccount(accountUser);
      //
      //   /// UserProvider
      //   QHYYUserProvider provider = QHYYUserProvider.instance;
      //   provider.accountUser = accountUser;
      //   provider.makeDataList();
      //   callback(true);
      // } else if (object.data["isSelf"] == 2) {
      //   // 重复认证
      //   QHYYAuthDuplicateDialog.show(object.data["user"]);
      //   callback(false);
      // } else {
      //   if (!TextUtil.isEmpty(imageUrl)) {
      //     showAlertDialog(
      //       alert: QHYYAlertMessage(title: "面容对比失败", content: "系统将使用头像进行人脸识别；如果不是账号本人，将无法登录使应用。"),
      //     );
      //   } else {
      //     showAlertDialog(
      //       alert: QHYYAlertMessage(title: "认证失败", content: "你的头像非本人\n请更新头像后再进行认证"),
      //     );
      //   }
      //   callback(false);
      // }
      requestAuthList();
      XinDongUserController.to.requestUserInfo();
      Get.back();
    }
    return Future.value();
  }

  //
  Future<bool> requestAuthVoice({required String filePath, required int duration}) async {
    if (filePath.isEmpty) {
      showToast('请录音');
      return false;
    }
    if (duration < 1) {
      showToast('录音时长太短');
      return false;
    }
    showLoading();
    final fileUrl = await XinDongNetworking.instance.uploadVideo(filePath: filePath);
    if (TextUtil.isEmpty(fileUrl)) {
      mDebugPrint('返回上传结果$fileUrl');
      hideLoading();
      return false;
    }
    final object = await XinDongNetworking.instance.request(
      XinDongApi.userEditInfo,
      method: XinDongHttpMethod.post,
      parameters: {"voice": fileUrl, "voice_time": duration},
    );
    hideLoading();
    if (object.code == XinDongServerStatus.success) {
      requestAuthList();
      XinDongUserController.to.requestUserInfo();
      Get.back();
      return true;
    }
    return false;
  }

  //
  Future<bool> requestAuthRealName({required List<File> files}) async {
    List<String> filePaths = files.map((e) => e.path).toList();
    return await _requestAuth(type: AuthType.realName, filePaths: filePaths);
  }

  //
  Future<bool> requestAuthCar({required List<XinDongSelectFileClass> fileClasss}) async {
    List<String> filePaths = fileClasss.map((e) => e.file.path).toList();
    return await _requestAuth(type: AuthType.car, filePaths: filePaths);
  }

  //
  Future<bool> requestAuthEducation({required List<XinDongSelectFileClass> fileClasss}) async {
    List<String> filePaths = fileClasss.map((e) => e.file.path).toList();
    return await _requestAuth(type: AuthType.education, filePaths: filePaths);
  }

  //
  Future<bool> requestAuthHouse({required List<XinDongSelectFileClass> fileClasss}) async {
    List<String> filePaths = fileClasss.map((e) => e.file.path).toList();
    return await _requestAuth(type: AuthType.house, filePaths: filePaths);
  }

  // 认证
  Future<bool> _requestAuth({required int type, required List<String> filePaths}) async {
    if (filePaths.isEmpty) {
      showToast('请上传相关证件图片');
      return false;
    }
    if (filePaths.length < 2) {
      showToast('请至少上传两张证件图片');
      return false;
    }
    showLoading();
    final fileUrl = await XinDongNetworking.instance.uploadFiles(filePaths: filePaths);
    if (TextUtil.isEmpty(fileUrl)) {
      mDebugPrint('返回图片结果$fileUrl');
      hideLoading();
      return false;
    }
    List<String> urlList = fileUrl!.stringToList();
    final object = await XinDongNetworking.instance.request(
      XinDongApi.userAuth,
      method: XinDongHttpMethod.post,
      parameters: {"types": type, "image_front": urlList.first, "image_behind": urlList.last},
    );
    hideLoading();
    if (object.code == XinDongServerStatus.success) {
      requestAuthList();
      XinDongUserController.to.requestUserInfo();
      Get.back();
      return true;
    }
    return false;
  }
}
